package com.rd.student.ruanjian.class3.gaochenxi.LianXi3.NumberSix;

public class NumberSix {
      private int num=1;
      private int set=1;

      //线程1
      /*
           解释下为什么会有while(set!=XXX)的东西:
           举例:
                   比如set=2时，因为只有printB()当中的while循环中set=2时不会进入while循环中
                   wait() ,所以其他线程得到set=2时都会wait，故此时只是执行了printB()当中的代码。
       */
      public synchronized void printA(){
            while(set!=1){
                  try {
                        wait();
                  } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                  }
            }
            System.out.println(Thread.currentThread().getName()+":");
            for(int i=1;i<=5;i++){
                  System.out.print(num+" ");
                  num++;
            }
            System.out.println();
            set++;
            notifyAll();
      }

      //线程2
      public synchronized void printB(){
            while(set!=2){
                  try {
                        wait();
                  } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                  }
            }
            System.out.println(Thread.currentThread().getName()+":");
            for(int i=1;i<=5;i++){
                  System.out.print(num+" ");
                  num++;
            }
            System.out.println();
            set++;
            notifyAll();
      }

      //线程3
      public synchronized void printC(){
            while(set!=3){
                  try {
                        wait();
                  } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                  }
            }
            System.out.println(Thread.currentThread().getName()+":");
            for(int i=1;i<=5;i++){
                  System.out.print(num+" ");
                  num++;
            }
            System.out.println();
            set=1;//重新赋值为1，返回到线程1开始
            notifyAll();
      }

      public static void main(String[] args) {
            NumberSix numberSix=new NumberSix();
            for(int i=0;i<5;i++){
                  new Thread(new Runnable() {
                        @Override
                        public void run() {
                              numberSix.printA();
                        }
                  },"线程1").start();

                  new Thread(new Runnable() {
                        @Override
                        public void run() {
                              numberSix.printB();
                        }
                  },"线程2").start();

                  new Thread(new Runnable() {
                        @Override
                        public void run() {
                              numberSix.printC();
                        }
                  },"线程3").start();
            }
      }
}
